package com.smilive.start.netty.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @program: netty
 * @Date: 2022-01-05 11:04
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class NettySimpleClient {

    public static void main(String[] args) throws Exception {
        asyncChannelClose();

    }

    /**
     *  异步监听等待等待close
     * @throws InterruptedException
     */
    private static void asyncChannelClose() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        //添加StringEncoder 字符串编码器
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8000))
                .sync();
        Channel channel = channelFuture.channel();

        Scanner scanner = new Scanner(System.in);
        new Thread(() ->{
            while (true){
                String msg = scanner.next();
                if ("q".equals(msg)){
                    channel.close();
                    break;
                }
                channel.writeAndFlush(msg);
            }
        },"input").start();

        //获得closeFuture对象
        ChannelFuture closeFuture = channel.closeFuture();
        log.debug("whatting close....");

        //异步监听关闭事件
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("channel closed....");
                group.shutdownGracefully();
            }
        });



    }

    /**
     *  同步阻塞等待close
     * @throws InterruptedException
     */
    private static void syncChannelClose() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        //添加StringEncoder 字符串编码器
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8000))
                .sync();
        Channel channel = channelFuture.channel();

        Scanner scanner = new Scanner(System.in);
        new Thread(() ->{
            while (true){
                String msg = scanner.next();
                if ("q".equals(msg)){
                    channel.close();
                    break;
                }
                channel.writeAndFlush(msg);
            }
        },"input").start();

        //获得closeFuture对象
        ChannelFuture closeFuture = channel.closeFuture();
        log.debug("whatting close....");

        //同步等待关闭结果
        closeFuture.sync();
        log.debug("channel closed....");

        group.shutdownGracefully();
    }

    /**
     *  异步监听获取 channel
     * @throws InterruptedException
     */
    private static void asyncChannel() throws InterruptedException, IOException {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                // 选择客户 Socket 实现类，NioSocketChannel 表示基于 NIO 的客户端实现
                .channel(NioSocketChannel.class)
                // ChannelInitializer 处理器（仅执行一次）
                // 它的作用是待客户端SocketChannel建立连接后，执行initChannel以便添加更多的处理器
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        //添加StringEncoder 字符串编码器
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8000))
                // 当connect方法执行完毕后，也就是连接真正建立后
                // 会在NIO线程中调用operationComplete方法
               .addListener(new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                       Channel channel = future.channel();
                       channel.writeAndFlush("hello world");
                   }
               });
        System.in.read();
    }

    /**
     *  同步阻塞获取 channel
     * @throws InterruptedException
     */
    private static void syncChannel() throws InterruptedException {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                // 选择客户 Socket 实现类，NioSocketChannel 表示基于 NIO 的客户端实现
                .channel(NioSocketChannel.class)
                // ChannelInitializer 处理器（仅执行一次）
                // 它的作用是待客户端SocketChannel建立连接后，执行initChannel以便添加更多的处理器
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        //添加StringEncoder 字符串编码器
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8000))
                // Netty 中很多方法都是异步的，如 connect
                // 这时需要使用 sync 同步阻塞方法等待 connect 建立连接完毕
                .sync()
                //获取 channel 对象，它即为通道抽象，可以进行数据读写操作
                .channel()
                // 写入消息并清空缓冲区
                .writeAndFlush("hello world");
    }
}
